package com.ruoyi.web.controller.redis;

import com.ruoyi.common.core.domain.AjaxResult;
import lombok.extern.slf4j.Slf4j;
import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @author zhenghuisheng
 * @date 2024/9/29 4:39
 */
@RestController
@RequestMapping("/test")
@Slf4j
public class StockController {

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private Redisson redisson;

    //手机id
    public static final String PHONE_ID = "phone:1001";
    //手机数量
    public static final String PHONE_COUNT = "phoneCount";

    @GetMapping("/disStock")
    public AjaxResult disStock(){
        String flag = UUID.randomUUID().toString();
        //定义一把分布式锁，设置有效期为30s
        RLock lock = redisson.getLock(PHONE_ID);
        lock.lock();
        try {
            //当前库存
            Integer stock = Integer.parseInt(redisTemplate.opsForValue().get(PHONE_COUNT) + "");
            if (stock > 0){
                stock = stock - 1;
                redisTemplate.opsForValue().set(PHONE_COUNT,stock);
                log.info("当前库存值为：" + stock);
            }else{
                log.info("当前库存为空，扣减失败");
            }
        }finally {
            lock.unlock();
        }
        return AjaxResult.success();
    }
}
